package com.cskt.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cskt.common.constants.ErrorCodeEnum;
import com.cskt.common.exception.ServiceException;
import com.cskt.service.SmsService;
import com.cskt.util.JsonUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.log4j.Log4j;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author mo
 * @Description:
 * @date 2020-09-21 15:58
 */

@Service
public class SmsServiceImpl implements SmsService {

    private static final Logger log = LoggerFactory.getLogger(SmsServiceImpl.class);
    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void sendMessage(String to, String code) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4G8HqKZt4CX645w7tvL2", "mbgbt7l1r3a9YRtJqwm5Wy4ED3eLIB");
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");

        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
//接收的手机号
        request.putQueryParameter("PhoneNumbers", to);
//短信签名名称
        request.putQueryParameter("SignName", "爱旅行");
//模板的编码
        request.putQueryParameter("TemplateCode", "SMS_205472666");
//需要发送的验证码
        Map<String,String> map =new HashMap<>();
        map.put("product",code);
        // String re = objectMapper.writeValueAsString(map);




        try {
            request.putQueryParameter("TemplateParam", JsonUtil.objectToJsonString(map));
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            log.info("调用短信发送接口响应数据 : {}",response.getData());
        } catch (ClientException e) {
            //封装成统一的异常并抛出
            log.error(e.getMessage(),e);
            throw new ServiceException(ErrorCodeEnum.ERROR_CALLING_THIRD_PARTY_SERVICE);

        }catch (JsonProcessingException e){
            //封装成统一的异常并抛出
            log.error(e.getMessage(),e);
            throw  new ServiceException(ErrorCodeEnum.SYSTEM_EXECUTION_ERROR);
        }

    }
}
